package com.yl.zqy.controller.sys;

import com.yl.zqy.common.CustomException;
import com.yl.zqy.common.Result;
import com.yl.zqy.entity.sys.SysDictType;
import com.yl.zqy.enums.ResultCode;
import com.yl.zqy.service.sys.SysDictDataService;
import com.yl.zqy.service.sys.SysDictTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 字典类型 前端控制器
 * </p>
 *
 * @author liang.yu
 * @since 2024-03-25
 */
@RestController
@RequestMapping("/sysDictType")
@Tag(name = "字典类型管理", description = "SysDictTypeController")
@RequiredArgsConstructor
public class SysDictTypeController {
    private final SysDictTypeService dictTypeService;
    private final SysDictDataService dictDataService;

    @PostMapping("/add")
    @Operation(summary = "新增字典类型", tags = "字典类型管理")
    public Result<Boolean> insertDictType(@RequestBody SysDictType dictType) {
        Optional.ofNullable(dictType.getDictCode()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "字典类型不能为空！"));
        return dictTypeService.insertDictType(dictType);
    }

    @PutMapping("/update")
    @Operation(summary = "修改字典类型", tags = "字典类型管理")
    public Result<Boolean> updateDictType(@RequestBody SysDictType dictType) {
        Optional.ofNullable(dictType.getId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "字典类型ID不能为空！"));
        Optional.ofNullable(dictType.getDictCode()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "字典类型不能为空！"));
        return dictTypeService.updateDictType(dictType);
    }

    @DeleteMapping("/deleteById/{id}")
    @Operation(summary = "删除字典类型", tags = "字典类型管理")
    public Result<Boolean> deleteDictTypeById(@Parameter(description = "id") @PathVariable(value = "id") String id) {
        Optional.ofNullable(id).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "字典类型ID不能为空！"));
        //判断是否有字典数据
        Long dataById = dictDataService.countDictDataById(id);
        if (dataById > 0) return Result.error(false, "当前字典类型下有值，不能删除！");
        boolean result = dictTypeService.removeById(id);
        if (result)
            return Result.ok();
        return Result.error("操作失败！");
    }

    @GetMapping("/dictTypeList")
    @Operation(summary = "获取字典类型列表", tags = "字典类型管理")
    public Result<List<SysDictType>> dictTypeList() {
        return dictTypeService.dictTypeList();
    }


}
